/*!
 * \file test_wts_logger.cpp
 * \project WonderTrader
 * 
 * \brief WTSLogger 日志系统测试套件
 * 
 * \details 测试WTSLogger类的所有功能：
 *          - 日志级别管理和过滤
 *          - printf风格和fmt::format风格接口
 *          - 分类日志输出
 *          - 动态日志器管理
 *          - 线程安全性
 *          - 配置文件初始化
 *          - 性能特性
 *          - 错误处理和边界条件
 */

#include <gtest/gtest.h>
#include <gmock/gmock.h>
#include "../../src/WTSTools/WTSLogger.h"
#include "../../src/Includes/WTSVariant.hpp"
#include <fstream>
#include <sstream>
#include <filesystem>
#include <thread>
#include <chrono>
#include <atomic>

/*!
 * \brief WTSLogger测试套件
 * 
 * \details 测试日志系统的核心功能：
 *          - 各种日志级别的输出
 *          - 不同格式化风格的接口
 *          - 分类和动态日志器
 *          - 并发安全性
 *          - 配置管理
 */
class WTSLoggerTest : public ::testing::Test {
protected:
    void SetUp() override {
        // 创建测试目录
        test_dir = "test_log_data";
        std::filesystem::create_directories(test_dir);
        
        // 创建测试配置文件
        createTestConfig();
        
        // 重定向标准输出以捕获日志
        original_cout_buf = std::cout.rdbuf();
        std::cout.rdbuf(captured_output.rdbuf());
    }
    
    void TearDown() override {
        // 恢复标准输出
        std::cout.rdbuf(original_cout_buf);
        
        // 停止日志系统
        WTSLogger::stop();
        WTSLogger::freeAllDynLoggers();
        
        // 清理测试文件
        std::filesystem::remove_all(test_dir);
    }
    
    /*!
     * \brief 创建测试配置文件
     */
    void createTestConfig() {
        std::ofstream config_file(test_dir + "/logcfg.json");
        config_file << R"({
            "root": {
                "level": "debug",
                "sinks": [
                    {
                        "type": "console",
                        "pattern": "[%Y-%m-%d %H:%M:%S.%e] [%l] %v"
                    },
                    {
                        "type": "file",
                        "filename": ")" << test_dir << R"(/test.log",
                        "pattern": "[%Y-%m-%d %H:%M:%S.%e] [%l] %v"
                    }
                ]
            },
            "loggers": {
                "test_category": {
                    "level": "info",
                    "sinks": [
                        {
                            "type": "file",
                            "filename": ")" << test_dir << R"(/test_category.log",
                            "pattern": "[%Y-%m-%d %H:%M:%S.%e] [%l] [%n] %v"
                        }
                    ]
                }
            }
        })";
        config_file.close();
    }
    
    /*!
     * \brief 获取捕获的输出内容
     */
    std::string getCapturedOutput() {
        return captured_output.str();
    }
    
    /*!
     * \brief 清空捕获的输出
     */
    void clearCapturedOutput() {
        captured_output.str("");
        captured_output.clear();
    }
    
    /*!
     * \brief 检查日志文件是否存在且包含指定内容
     */
    bool checkLogFileContains(const std::string& filename, const std::string& content) {
        std::ifstream file(filename);
        if (!file.is_open()) return false;
        
        std::string line;
        while (std::getline(file, line)) {
            if (line.find(content) != std::string::npos) {
                return true;
            }
        }
        return false;
    }

protected:
    std::string test_dir;
    std::stringstream captured_output;
    std::streambuf* original_cout_buf;
};

/*!
 * \brief 测试基本日志级别输出
 */
TEST_F(WTSLoggerTest, TestBasicLogLevels) {
    // 测试各种日志级别的原始输出
    WTSLogger::log_raw(LL_DEBUG, "Debug message");
    WTSLogger::log_raw(LL_INFO, "Info message");
    WTSLogger::log_raw(LL_WARN, "Warning message");
    WTSLogger::log_raw(LL_ERROR, "Error message");
    WTSLogger::log_raw(LL_FATAL, "Fatal message");
    
    // 验证输出不为空（具体内容取决于是否初始化）
    EXPECT_NO_THROW({
        WTSLogger::log_raw(LL_DEBUG, "Test debug");
        WTSLogger::log_raw(LL_INFO, "Test info");
        WTSLogger::log_raw(LL_WARN, "Test warn");
        WTSLogger::log_raw(LL_ERROR, "Test error");
        WTSLogger::log_raw(LL_FATAL, "Test fatal");
    });
}

/*!
 * \brief 测试printf风格接口
 */
TEST_F(WTSLoggerTest, TestPrintfStyleAPIs) {
    // 测试基本printf风格日志
    EXPECT_NO_THROW({
        WTSLogger::debug("Debug: %s %d", "test", 123);
        WTSLogger::info("Info: %s %d", "test", 456);
        WTSLogger::warn("Warning: %s %d", "test", 789);
        WTSLogger::error("Error: %s %d", "test", 101112);
        WTSLogger::fatal("Fatal: %s %d", "test", 131415);
    });
    
    // 测试通用log接口
    EXPECT_NO_THROW({
        WTSLogger::log(LL_DEBUG, "Generic debug: %d", 1);
        WTSLogger::log(LL_INFO, "Generic info: %d", 2);
        WTSLogger::log(LL_WARN, "Generic warn: %d", 3);
        WTSLogger::log(LL_ERROR, "Generic error: %d", 4);
        WTSLogger::log(LL_FATAL, "Generic fatal: %d", 5);
    });
}

/*!
 * \brief 测试fmt::format风格接口
 */
TEST_F(WTSLoggerTest, TestFmtFormatStyleAPIs) {
    // 测试fmt::format风格日志
    EXPECT_NO_THROW({
        WTSLogger::debug_f("Debug: {} {}", "test", 123);
        WTSLogger::info_f("Info: {} {}", "test", 456);
        WTSLogger::warn_f("Warning: {} {}", "test", 789);
        WTSLogger::error_f("Error: {} {}", "test", 101112);
        WTSLogger::fatal_f("Fatal: {} {}", "test", 131415);
    });
    
    // 测试通用log_f接口
    EXPECT_NO_THROW({
        WTSLogger::log_f(LL_DEBUG, "Generic debug: {}", 1);
        WTSLogger::log_f(LL_INFO, "Generic info: {}", 2);
        WTSLogger::log_f(LL_WARN, "Generic warn: {}", 3);
        WTSLogger::log_f(LL_ERROR, "Generic error: {}", 4);
        WTSLogger::log_f(LL_FATAL, "Generic fatal: {}", 5);
    });
}

/*!
 * \brief 测试分类日志输出
 */
TEST_F(WTSLoggerTest, TestCategoryLogging) {
    const char* category = "test_category";
    
    // 测试分类日志原始输出
    EXPECT_NO_THROW({
        WTSLogger::log_raw_by_cat(category, LL_DEBUG, "Category debug message");
        WTSLogger::log_raw_by_cat(category, LL_INFO, "Category info message");
        WTSLogger::log_raw_by_cat(category, LL_WARN, "Category warning message");
        WTSLogger::log_raw_by_cat(category, LL_ERROR, "Category error message");
        WTSLogger::log_raw_by_cat(category, LL_FATAL, "Category fatal message");
    });
    
    // 测试分类日志printf风格
    EXPECT_NO_THROW({
        WTSLogger::log_by_cat(category, LL_INFO, "Category printf: %s %d", "test", 123);
        WTSLogger::log_by_cat(category, LL_WARN, "Category printf: %s %d", "warn", 456);
    });
    
    // 测试分类日志fmt::format风格
    EXPECT_NO_THROW({
        WTSLogger::log_by_cat_f(category, LL_INFO, "Category format: {} {}", "test", 123);
        WTSLogger::log_by_cat_f(category, LL_ERROR, "Category format: {} {}", "error", 456);
    });
}

/*!
 * \brief 测试动态日志器
 */
TEST_F(WTSLoggerTest, TestDynamicLoggers) {
    const char* pattern = "[%Y-%m-%d %H:%M:%S] [%l] %v";
    const char* logger_name = "dynamic_logger";
    
    // 测试动态日志器原始输出
    EXPECT_NO_THROW({
        WTSLogger::log_dyn_raw(pattern, logger_name, LL_INFO, "Dynamic raw message");
        WTSLogger::log_dyn_raw(pattern, logger_name, LL_ERROR, "Dynamic raw error");
    });
    
    // 测试动态日志器printf风格
    EXPECT_NO_THROW({
        WTSLogger::log_dyn(pattern, logger_name, LL_INFO, "Dynamic printf: %s %d", "test", 123);
        WTSLogger::log_dyn(pattern, logger_name, LL_WARN, "Dynamic printf: %s %d", "warn", 456);
    });
    
    // 测试动态日志器fmt::format风格
    EXPECT_NO_THROW({
        WTSLogger::log_dyn_f(pattern, logger_name, LL_INFO, "Dynamic format: {} {}", "test", 123);
        WTSLogger::log_dyn_f(pattern, logger_name, LL_ERROR, "Dynamic format: {} {}", "error", 456);
    });
}

/*!
 * \brief 测试中文字符处理
 */
TEST_F(WTSLoggerTest, TestChineseCharacters) {
    EXPECT_NO_THROW({
        WTSLogger::info("中文信息: %s", "测试内容");
        WTSLogger::warn_f("中文警告: {}", "警告内容");
        WTSLogger::error("中文错误: 错误代码 %d", 404);
        WTSLogger::log_by_cat("中文分类", LL_INFO, "分类日志: %s", "中文内容");
        WTSLogger::log_dyn_f("[%l] %v", "中文动态", LL_DEBUG, "动态日志: {}", "中文测试");
    });
}

/*!
 * \brief 测试空值和特殊字符处理
 */
TEST_F(WTSLoggerTest, TestNullAndSpecialCharacters) {
    // 测试空字符串
    EXPECT_NO_THROW({
        WTSLogger::info("");
        WTSLogger::debug_f("");
        WTSLogger::log_raw(LL_INFO, "");
    });
    
    // 测试特殊字符
    EXPECT_NO_THROW({
        WTSLogger::info("Special chars: \n\t\r\\\"");
        WTSLogger::warn_f("Format special: {} {} {}", "\n", "\t", "\\");
        WTSLogger::error("Percent signs: %% %s %%", "test");
    });
    
    // 测试长字符串
    std::string long_string(5000, 'A');
    EXPECT_NO_THROW({
        WTSLogger::info("Long string: %s", long_string.c_str());
        WTSLogger::debug_f("Long format: {}", long_string);
    });
}

/*!
 * \brief 测试边界条件和错误处理
 */
TEST_F(WTSLoggerTest, TestBoundaryConditionsAndErrorHandling) {
    // 测试无效日志级别
    EXPECT_NO_THROW({
        WTSLogger::log_raw(static_cast<WTSLogLevel>(999), "Invalid level");
        WTSLogger::log(static_cast<WTSLogLevel>(-1), "Negative level: %d", -1);
    });
    
    // 测试空指针参数
    EXPECT_NO_THROW({
        WTSLogger::log_raw_by_cat(nullptr, LL_INFO, "Null category");
        WTSLogger::log_dyn_raw(nullptr, "test", LL_INFO, "Null pattern");
        WTSLogger::log_dyn_raw("[%l] %v", nullptr, LL_INFO, "Null logger name");
    });
    
    // 测试格式化错误（应该安全处理）
    EXPECT_NO_THROW({
        WTSLogger::info("Missing arg: %s %d", "only_one");
        WTSLogger::debug_f("Wrong format: {} {} {}", "only", "two");
    });
}

/*!
 * \brief 测试线程安全性
 */
TEST_F(WTSLoggerTest, TestThreadSafety) {
    const int num_threads = 8;
    const int messages_per_thread = 100;
    std::vector<std::thread> threads;
    std::atomic<int> success_count{0};
    
    // 创建多个线程同时写日志
    for (int i = 0; i < num_threads; ++i) {
        threads.emplace_back([&, i]() {
            try {
                for (int j = 0; j < messages_per_thread; ++j) {
                    WTSLogger::info("Thread %d message %d", i, j);
                    WTSLogger::debug_f("Thread {} debug {}", i, j);
                    WTSLogger::log_by_cat("thread_test", LL_WARN, "Thread %d warning %d", i, j);
                    WTSLogger::log_dyn_f("[%l] %v", "thread_dyn", LL_ERROR, "Thread {} error {}", i, j);
                }
                success_count++;
            } catch (...) {
                // 线程安全测试不应该抛出异常
            }
        });
    }
    
    // 等待所有线程完成
    for (auto& thread : threads) {
        thread.join();
    }
    
    // 验证所有线程都成功完成
    EXPECT_EQ(success_count.load(), num_threads);
}

/*!
 * \brief 测试性能特性
 */
TEST_F(WTSLoggerTest, TestPerformanceCharacteristics) {
    const int num_messages = 10000;
    
    // 测试printf风格性能
    auto start_time = std::chrono::high_resolution_clock::now();
    for (int i = 0; i < num_messages; ++i) {
        WTSLogger::debug("Performance test message %d with data %s", i, "test_data");
    }
    auto end_time = std::chrono::high_resolution_clock::now();
    auto printf_duration = std::chrono::duration_cast<std::chrono::milliseconds>(end_time - start_time);
    
    // 测试fmt::format风格性能
    start_time = std::chrono::high_resolution_clock::now();
    for (int i = 0; i < num_messages; ++i) {
        WTSLogger::debug_f("Performance test message {} with data {}", i, "test_data");
    }
    end_time = std::chrono::high_resolution_clock::now();
    auto format_duration = std::chrono::duration_cast<std::chrono::milliseconds>(end_time - start_time);
    
    std::cout << "性能测试结果 (" << num_messages << " 条消息):" << std::endl;
    std::cout << "  printf风格: " << printf_duration.count() << "ms" << std::endl;
    std::cout << "  format风格: " << format_duration.count() << "ms" << std::endl;
    
    // 性能测试：应该在合理时间内完成（比如5秒内）
    EXPECT_LT(printf_duration.count(), 5000);
    EXPECT_LT(format_duration.count(), 5000);
}

/*!
 * \brief 测试内存使用和资源管理
 */
TEST_F(WTSLoggerTest, TestMemoryUsageAndResourceManagement) {
    // 创建大量动态日志器
    const int num_loggers = 100;
    std::vector<std::string> logger_names;
    
    for (int i = 0; i < num_loggers; ++i) {
        std::string logger_name = "test_logger_" + std::to_string(i);
        logger_names.push_back(logger_name);
        
        // 使用动态日志器
        WTSLogger::log_dyn_f("[%l] %v", logger_name.c_str(), LL_INFO, "Logger {} message", i);
    }
    
    // 释放所有动态日志器
    EXPECT_NO_THROW({
        WTSLogger::freeAllDynLoggers();
    });
    
    // 再次使用应该重新创建
    for (const auto& name : logger_names) {
        EXPECT_NO_THROW({
            WTSLogger::log_dyn(name.c_str(), name.c_str(), LL_DEBUG, "Recreated logger message");
        });
    }
}

/*!
 * \brief 测试日志系统停止和重启
 */
TEST_F(WTSLoggerTest, TestStopAndRestart) {
    // 正常日志输出
    WTSLogger::info("Before stop");
    
    // 停止日志系统
    EXPECT_NO_THROW({
        WTSLogger::stop();
    });
    
    // 停止后仍应该能安全调用（可能不输出或输出到控制台）
    EXPECT_NO_THROW({
        WTSLogger::info("After stop");
        WTSLogger::debug_f("After stop format: {}", "test");
        WTSLogger::log_by_cat("test", LL_WARN, "After stop category");
    });
    
    // 多次停止应该安全
    EXPECT_NO_THROW({
        WTSLogger::stop();
        WTSLogger::stop();
    });
}

/*!
 * \brief 测试极端条件
 */
TEST_F(WTSLoggerTest, TestExtremeConditions) {
    // 测试大量快速日志输出
    EXPECT_NO_THROW({
        for (int i = 0; i < 1000; ++i) {
            WTSLogger::debug("Rapid message %d", i);
            WTSLogger::info_f("Rapid format {}", i);
            WTSLogger::log_by_cat("rapid", LL_WARN, "Rapid category %d", i);
        }
    });
    
    // 测试嵌套格式化
    EXPECT_NO_THROW({
        WTSLogger::info("Nested: %s", "outer");
        WTSLogger::debug_f("Nested: {}", "format");
    });
    
    // 测试递归调用（在日志回调中再次调用日志）
    // 注意：这可能导致无限递归，实际实现应该有保护机制
    EXPECT_NO_THROW({
        WTSLogger::warn("Potential recursive call test");
    });
}

/*!
 * \brief 测试日志级别过滤
 */
TEST_F(WTSLoggerTest, TestLogLevelFiltering) {
    // 测试所有级别都能正常调用（具体是否输出取决于配置）
    EXPECT_NO_THROW({
        WTSLogger::debug("Debug level message");
        WTSLogger::info("Info level message");
        WTSLogger::warn("Warning level message");
        WTSLogger::error("Error level message");
        WTSLogger::fatal("Fatal level message");
    });
    
    // 测试级别过滤不会影响程序稳定性
    for (int level = LL_DEBUG; level <= LL_FATAL; ++level) {
        EXPECT_NO_THROW({
            WTSLogger::log(static_cast<WTSLogLevel>(level), "Level %d message", level);
            WTSLogger::log_f(static_cast<WTSLogLevel>(level), "Level {} format", level);
        });
    }
}

/*!
 * \brief 测试格式化字符串的复杂性
 */
TEST_F(WTSLoggerTest, TestComplexFormatting) {
    // 测试复杂的printf格式化
    EXPECT_NO_THROW({
        WTSLogger::info("Complex printf: %d %s %.2f %x %o", 123, "test", 3.14159, 255, 64);
        WTSLogger::debug("Width and precision: %10s %5d %8.3f", "test", 42, 3.14159);
        WTSLogger::warn("Left align: %-10s %-5d", "left", 123);
    });
    
    // 测试复杂的fmt::format格式化
    EXPECT_NO_THROW({
        WTSLogger::info_f("Complex format: {} {} {:.2f} {:x} {:o}", 123, "test", 3.14159, 255, 64);
        WTSLogger::debug_f("Width and precision: {:>10} {:>5} {:>8.3f}", "test", 42, 3.14159);
        WTSLogger::warn_f("Left align: {:<10} {:<5}", "left", 123);
    });
    
    // 测试特殊格式化情况
    EXPECT_NO_THROW({
        WTSLogger::error("Percent literal: 100%% complete");
        WTSLogger::fatal_f("Brace literal: {{}} and {}", "value");
    });
} 